package com.androway.widget;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.androway.activity.R;
import com.androway.domains.News;
import com.androway.model.ApplicationModel;

public class NewsAdapter extends BaseAdapter
{

	private class NewsView
	{
		TextView title;
		TextView content;
		ImageView photo;

	}

	private List<News> newsList;
	private LayoutInflater inflater;

	public NewsAdapter(Context context, List<News> news)
	{
		newsList = news;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount()
	{
		return newsList.size();
	}

	@Override
	public Object getItem(int position)
	{
		return newsList.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	private Bitmap getBitmap(String str)
	{
		try
		{
			Bitmap bitmap;
			InputStream input;
			URL url = new URL(str);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setDoInput(true);
			con.connect();
			input = con.getInputStream();
			bitmap = BitmapFactory.decodeStream(input);
			return bitmap;

		}
		catch (MalformedURLException e)
		{
			return null;
		}
		catch (IOException e)
		{
			return null;
		}
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		final NewsView view;

		if (convertView == null)
		{
			Bitmap bitmap;

			view = new NewsView();
			convertView = inflater.inflate(R.layout.news_widget, null);
			view.content = (TextView) convertView.findViewById(R.id.content);
			view.title = (TextView) convertView.findViewById(R.id.title);
			view.photo = (ImageView) convertView.findViewById(R.id.photoNews);
			convertView.setTag(view);
			bitmap = this.getBitmap(ApplicationModel.getPhotoUrl(newsList.get(position).getAuthor()));
			if (bitmap != null)
				view.photo.setImageBitmap(bitmap);
			view.content.setText(newsList.get(position).getContent());
			view.title.setText(newsList.get(position).getTitle());
		}
		else
		{
			view = (NewsView) convertView.getTag();
		}
		return convertView;
	}

	public void update(List<News> newsData)
	{
		// TODO Auto-generated method stub

	}
}
